<script lang="ts" setup>
import { ref, computed, Ref } from "vue";
import { Edit } from "@element-plus/icons-vue";
import Assistant from "@/types/response/assistant";
import { ElMessage } from "element-plus";
import {
  createAssistant,
  updateAssistant,
  getAllAssistant,
} from "@/axios/assistant/assistantReq";
import { changeUserState, getUserStatesByIds } from "@/axios/admin/accountReq";
import Notice from "@/utils/notice";

interface ExtendedAssistant extends Assistant {
  state?: number;
}

const gender = [
  {
    value: 1,
    label: "男",
  },
  {
    value: 0,
    label: "女",
  },
];

const stateOptions = [
  {
    value: 1,
    label: "启用",
  },
  {
    value: 0,
    label: "停用",
  },
];
//用户搜索时输入的名字
const name = ref("");

const rulesFormRef = ref();

const assistants: Ref<Assistant[]> = ref([]);

// 控制添加助理弹窗
const dialogVisible = ref(false);

// 添加助理数据模型
const assistantModel = ref<ExtendedAssistant>(new Assistant());

// 性别选择框绑定的值
const genderValue = ref<number>();

// 状态选择框绑定的值
const stateValue = ref<number>();

// 获取助理列表
const getAssistants = async () => {
  let result = await getAllAssistant();
  assistants.value = result;
  let states = await getUserStatesByIds(
    assistants.value.map((assistants) => assistants.assistantId)
  );

  assistants.value = assistants.value.map((assistants) => ({
    ...assistants,
    state: states.get(assistants.assistantId) || undefined,
  }));
};
getAssistants();

// 添加助理表单校验
const rules = {
  name: [{ required: true, message: "请输入助理姓名", trigger: "blur" }],
  gender: [{ required: true, message: "请选择性别", trigger: "change" }],
  phoneNum: [{ required: true, message: "请输入手机号", trigger: "blur" }],
  idNum: [{ required: true, message: "请输入身份证号", trigger: "blur" }]
};

//添加助理函数
const addAssistant = () => {
  title.value = "新增助理";
  assistantModel.value = new Assistant();
  dialogVisible.value = true;
  genderValue.value = 1;
  editIndex.value = null;
  rulesFormRef.value?.resetFields();
};
const editIndex = ref<number | null>(null);

const editAssistant = (index: number, assistant: ExtendedAssistant) => {
  title.value = "编辑助理";
  dialogVisible.value = true;
  assistantModel.value = { ...assistant };
  genderValue.value = assistant.gender;
  editIndex.value = index;
  rulesFormRef.value?.clearValidate();
};

const validateForm = () => {
  rulesFormRef.value.validate((valid) => {
    if (valid) {
      submitForm();
    }
  });
};

// 提交表单的方法
const submitForm = async () => {
  if (genderValue.value) {
    assistantModel.value.gender = genderValue.value;
  }
  if (stateValue.value) {
    assistantModel.value.state = stateValue.value;
  }
  if (editIndex.value !== null) {
    //更新助理信息
    const success = await updateAssistant(assistantModel.value);
    if (success) {
      assistants.value[editIndex.value] = { ...assistantModel.value };
      editIndex.value = null;
      ElMessage({
        type: "success",
        message: "更新信息成功",
      });
    } else {
      ElMessage({
        type: "error",
        message: "更新信息失败",
      });
    }
  } else {
    // 设置创建时间为当前时间
    assistantModel.value.createdTime = new Date().toISOString();
    //添加助理信息
    const newAssistant = await createAssistant(assistantModel.value); // 调用 createAssistant 函数

    if (newAssistant) {
      assistants.value.push(newAssistant);
      Notice.success("创建成功");
    } else {
      Notice.error("创建失败");
    }
    genderValue.value = 1;
    stateValue.value = 1;
  }

  // 这里可以添加保存到 assistants 数组的逻辑
  dialogVisible.value = false;
};

// 切换助理状态的方法
const toggleState = async (assistant: any) => {
  try {
    const newState = assistant.state === 1 ? 0 : 1;
    const success = await changeUserState(assistant.assistantId, newState);
    if (success) {
      assistant.state = newState;
      ElMessage({
        type: "success",
        message: "状态切换成功",
      });
    } else {
      ElMessage({
        type: "error",
        message: "状态切换失败",
      });
    }
  } catch (error) {
    console.error("切换状态时出错:", error);
  }
};

const title = ref("");

const filteredAssistants = computed(() => {
  return assistants.value.filter(
    (assistant) => !name.value || assistant.name.includes(name.value)
  );
});
</script>

<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>助理管理</span>
        <div class="extra">
          <el-button type="primary" @click="addAssistant">新增助理</el-button>
        </div>
      </div>
    </template>
    <!-- 搜素表单 -->
    <el-form inline>
      <el-form-item label="姓名：">
        <el-input
          v-model="name"
          style="width: 240px"
          clearable
          placeholder="请输入筛选姓名"
        />
      </el-form-item>
    </el-form>

    <el-table :data="filteredAssistants" style="width: 100%">
      <el-table-column type="index" label="序号" width="100"></el-table-column>
      <el-table-column label="姓名" prop="name"></el-table-column>
      <el-table-column label="性别" prop="gender">
        <template #default="scope">
          {{
            gender.find((g) => g.value === scope.row.gender)?.label || "未知"
          }}
        </template>
      </el-table-column>
      <el-table-column label="手机号" prop="phoneNum"></el-table-column>
      <el-table-column label="状态" prop="state">
        <template #default="scope">
          {{ scope.row.state === 1 ? "启用" : "停用" }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button
            :icon="Edit"
            circle
            plain
            type="primary"
            :disabled="scope.row.state === 0"
            @click="editAssistant(scope.$index, scope.row)"
          ></el-button>
          <el-button
            :type="scope.row.state === 1 ? 'danger' : 'success'"
            circle
            plain
            @click="toggleState(scope.row)"
          >
            {{
              stateOptions.find((s) => s.value === scope.row.state)?.label ===
              "启用"
                ? "停用"
                : "启用"
            }}
          </el-button>
        </template>
      </el-table-column>
      <template #empty>
        <el-empty description="没有数据" />
      </template>
    </el-table>
    <el-dialog v-model="dialogVisible" :title="title" width="30%">
      <el-form
        :model="assistantModel"
        :rules="rules"
        label-width="100px"
        style="padding-right: 30px"
        ref="rulesFormRef"
      >
        <el-form-item label="助理姓名" prop="name">
          <el-input
            v-model="assistantModel.name"
            minlength="2"
            maxlength="10"
          ></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="genderValue" placeholder="请选择性别">
            <el-option
              v-for="item in gender"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="身份证号" prop="idNum">
          <el-input
            v-model="assistantModel.idNum"
            minlength="18"
            maxlength="18"
          ></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phoneNum">
          <el-input
            v-model="assistantModel.phoneNum"
            :disabled="editIndex !== null"
            minlength="11"
            maxlength="11"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="validateForm">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </el-card>
</template>

<style lang="scss" scoped>
.page-container {
  min-height: 100%;
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}
</style>
